<template>
  <div :class="className" :style="{ height: height, width: width }"/>
</template>

<script setup>
import * as echarts from 'echarts'
//获取store和router
let {proxy} = getCurrentInstance()
const props = defineProps({
  className: {
    type: String,
    default: 'chart'
  },
  width: {
    type: String,
    default: '100%'
  },
  height: {
    type: String,
    default: '350px'
  },
  autoResize: {
    type: Boolean,
    default: true
  },
  chartData: {
    type: Object,
    required: true
  }
})
const state = reactive({
  chart: null
})
const inited = ref(false);

onBeforeUnmount(() => {
  if (!state.chart) {
    return
  }
  state.chart.dispose()
  state.chart = null
})
const initChart = () => {
  // 不能设置绑定动态数据，等有了数据再加载
  state.chart = markRaw(echarts.init(proxy.$el, 'macarons'));
  inited.value = true;
  setOptions(props.chartData)
}
const setOptions = ({thisYear, lastYear} = {}) => {
  state.chart.setOption({
    title: {
      text: props.chartData.titleText,
      padding: [0, 10]
    },
    legend: {
      show: true
    },
    grid: {
      left: 10,
      right: 10,
      bottom: 15,
      top: 30,
      containLabel: true
    },
    tooltip: {
      trigger: 'item',
      axisPointer: {
        type: 'cross'
      },
      padding: [5, 10]
    },
    xAxis: {
      data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
      boundaryGap: false,
      axisTick: {
        show: true
      }
    },
    yAxis: {
      axisTick: {
        show: true
      }
    },
    series: [
      {
        name: '今年',
        itemStyle: {
          normal: {
            color: '#FF005A',
            lineStyle: {
              color: '#FF005A',
              width: 2
            }
          }
        },
        smooth: true,
        type: 'line',
        data: thisYear,
        animationDuration: 2800,
        animationEasing: 'cubicInOut'
      },
      {
        name: '去年',
        smooth: true,
        type: 'line',
        itemStyle: {
          normal: {
            color: '#3888fa',
            lineStyle: {
              color: '#3888fa',
              width: 2
            },
            areaStyle: {
              color: '#f3f8ff'
            }
          }
        },
        data: lastYear,
        animationDuration: 2800,
        animationEasing: 'quadraticOut'
      }
    ]
  })
}
//导出属性到页面中使用
// let {levelList} = toRefs(state);
defineExpose({initChart})
</script>

<style scoped lang="scss">
.chart {
  background-color: white;
}
</style>
